<?php


namespace EchoPHP\View;


use EchoPHP\Facades\File;
use EchoPHP\Foundation\Application;
use League\Plates\Engine;

class View extends Engine {

    /**
     * 应用程序实例
     * @var Application
     */
    protected $app;

    /**
     * 默认模板文件夹路径
     * @var string
     */
    protected $defaultDirectory;

    /**
     * 项目根目录末班文件夹路径
     * @var
     */
    protected $rootDirectory;

    /**
     * 默认模板文件后缀
     * @var
     */
    protected $defaultFileExtension;


    public function __construct(Application $app, $directory = null, $fileExtension = null) {
        $this->app = $app;
        $this->setDefaultDirectory($directory);
        $this->setDefaultFileExtension($fileExtension);
        parent::__construct($this->defaultDirectory, $this->defaultFileExtension);


        $this->setRootDirectory();
        $this->addFolder('root', $this->rootDirectory);
    }

    /**
     * 设置模板文件存放根目录
     * @param string $directory
     * @return mixed|object
     * @throws \Exception
     */
    protected function setDefaultDirectory($directory = null) {
        if (is_null($directory)) {
            $this->defaultDirectory = $this->app->make('path.view') . config('view.directory', '');
        } else {
            $this->defaultDirectory = $directory;
        }
        if (!File::isDirectory($this->defaultDirectory)) {
            File::makeDirectory($this->defaultDirectory, 0755, true, true);
        }
    }

    /**
     * 设置根目录
     * @return mixed
     * @throws \Exception
     */
    protected function setRootDirectory() {
        $this->rootDirectory = $this->app->make('path.view');
        if (!File::isDirectory($this->rootDirectory)) {
            File::makeDirectory($this->rootDirectory, 0755, true, true);
        }
    }

    /**
     * 设置模板文件后缀
     * @param string $fileExtension
     * @return \EchoPHP\Foundation\Container|mixed|object|string
     * @throws \Exception
     */
    protected function setDefaultFileExtension($fileExtension = null) {
        if (empty($fileExtension)) {
            $fileExtension = config('view.extension', 'php');
        }
        $this->defaultFileExtension = $fileExtension;
    }


}